import os
import re
import json
from typing import List, Tuple, Optional




def find_continuous_ranges(directory: str) -> List[Tuple[int, int]]:
    """查找目录中的连续数字文件区间"""
    numbers = []
    pattern = re.compile(r'^(\d+)\.jpg$', re.IGNORECASE)
    
    for filename in os.listdir(directory):
        match = pattern.match(filename)
        if match:
            try:
                num = int(match.group(1))
                numbers.append(num)
            except ValueError:
                continue
    
    if not numbers:
        return []
    
    numbers.sort()
    
    ranges = []
    current_start = current_end = numbers[0]
    
    for num in numbers[1:]:
        if num == current_end + 1:
            current_end = num
        else:
            ranges.append((current_start, current_end))
            current_start = current_end = num
    ranges.append((current_start, current_end))
    
    return ranges

def generate_range_json(directory: str):
    """
    在指定目录生成range.json文件
    格式：[
        {"start": 2525, "end": 2532, "factor": 0.1},
        {"start": 2533, "end": null, "factor": 1.0}
    ]
    """
    ranges = find_continuous_ranges(directory)
    ranges.sort(key=lambda x: x[0])
    
    speed_segments = []
    prev_end = -1
    
    # 生成速度参数
    for start, end in ranges:
        if prev_end < start - 1:
            speed_segments.append({
                "start": prev_end + 1,
                "end": start - 1,
                "factor": 1.0
            })
        
        speed_segments.append({
            "start": start,
            "end": end,
            "factor": 0.1
        })
        prev_end = end
    
    # 添加结尾段
    if ranges:
        speed_segments.append({
            "start": ranges[-1][1] + 1,
            "end": None,
            "factor": 1.0
        })
    
    # 写入文件
    img_dir = "/data/control_communication/chunk_0000/chunk_0000_mp4/problem_cross"
    output_path = os.path.join(img_dir, "range.json")
    with open(output_path, "w") as f:
        json.dump(speed_segments, f, indent=2)
    
    print(f"已生成配置文件: {output_path}")


def find_continuous_ranges(directory: str) -> List[Tuple[int, int]]:
    """查找目录中的连续数字文件区间"""
    numbers = []
    pattern = re.compile(r'^(\d+)\.jpg$', re.IGNORECASE)
    
    for filename in os.listdir(directory):
        match = pattern.match(filename)
        if match:
            try:
                num = int(match.group(1))
                numbers.append(num)
            except ValueError:
                continue
    
    if not numbers:
        return []
    
    numbers.sort()
    
    ranges = []
    current_start = current_end = numbers[0]
    
    for num in numbers[1:]:
        if num == current_end + 1:
            current_end = num
        else:
            ranges.append((current_start, current_end))
            current_start = current_end = num
    ranges.append((current_start, current_end))
    
    return ranges

def get_max_image_number(directory: str) -> Optional[int]:
    """
    返回文件夹中数字最大的图像文件名编号
    (文件名格式为纯数字+.jpg，例如 123.jpg)
    如果没有符合条件的文件，返回 None
    """
    max_num = -1
    pattern = re.compile(r'^(\d+)\.jpg$', re.IGNORECASE)
    
    for filename in os.listdir(directory):
        match = pattern.match(filename)
        if match:
            try:
                num = int(match.group(1))
                if num > max_num:
                    max_num = num
            except ValueError:
                continue
    
    return max_num if max_num != -1 else None

# 使用示例
if __name__ == "__main__":
    target_dir = "/data/control_communication/chunk_0000/chunk_0000_mp4/problem_cross"
    max_dir = "/data/control_communication/results/video"

    # 生成range.json文件
    generate_range_json(target_dir)
    max_number = get_max_image_number(max_dir)
    print(f"最大图像编号: {max_number}")
